package com.labofjet.system.filter;

import com.labofjet.common.service.RedisService;
import com.labofjet.system.dto.SysUserDto;
import com.labofjet.system.enums.ERedisDefine;
import com.labofjet.system.enums.ESessionDefine;
import com.labofjet.system.enums.EState;
import com.labofjet.system.service.impl.SysUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * session超时以后,如果有token就自动查询用户数据插入session,用于记住登陆信息
 */
@WebFilter(filterName = "tokenFilter", urlPatterns = "/*")
public class TokenFilter implements Filter {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SysUserServiceImpl sysUserService;

	@Autowired
	private RedisService redisService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		log.debug("TokenFilter 初始化");
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(false);
		try {
			if (session == null || session.getAttribute(ESessionDefine.CURRENT_USER.getCode()) == null) {
				Cookie[] cookies = request.getCookies();
				String token = "";
				if (cookies == null) {
					filterChain.doFilter(servletRequest, servletResponse);
					return;
				}
				for (Cookie cookie : cookies) {
					if ("token".equals(cookie.getName())) {
						token = cookie.getValue();
					}
				}
				if (StringUtils.isNotEmpty(token)) { // 存在token
					//不存在...
					String tokenUser = redisService.get(ERedisDefine.TOKEN_PREFIX.getCode() + token);
					if (StringUtils.isEmpty(tokenUser)) {
						filterChain.doFilter(servletRequest, servletResponse);
						return;
					}

					// 存在
					String[] s = new String(Base64Utils.decode(token.getBytes())).split("\\|");
					String tokenUsername = s[0];
					SysUserDto sysUserDto = new SysUserDto();
					sysUserDto.setUsername(tokenUsername);
					sysUserDto = sysUserService.findByUsername(sysUserDto);
                    sysUserService.loadPermissionsAndRoles(sysUserDto);
                    if (!EState.VALID.getCode().equals(sysUserDto.getState())) { // 用户被锁定的
						filterChain.doFilter(servletRequest, servletResponse);
						return;
					}
					session = request.getSession(true);
					session.setAttribute(ESessionDefine.CURRENT_USER.getCode(), sysUserDto);
				}
			}
		} catch (Exception e) {
			log.error("token登录出现异常", e);
			throw new RuntimeException(e);
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void destroy() {

	}
}
